package com.gjl.app.oauth.common;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;


public class OauthUtil {
	
	public static final String UTF_8 = "UTF-8";
	
	private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
	
	public static String generateTs() {
		return String.valueOf(System.currentTimeMillis()/1000);
	}

	public static String generateNonce() {
		return String.valueOf(System.nanoTime());
	}
	
	public static String urlEncode(String toBeEncoded) {
		String result = null;
		try {
			result = URLEncoder.encode(toBeEncoded, UTF_8);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public static String hmac(String data, String key) {
		String result = null;
		SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
		try {
			Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
			mac.init(signingKey);
			byte[] rawHmac = mac.doFinal(data.getBytes());
			result = Base64.encodeBase64String(rawHmac);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} 
		return result;
	}
	
}
